<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\LoginLogRepository;
use App\Repositories\Permission\AdminRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    protected array $validateRules = [
        'phone' => 'required|string|regex:/^1[345789]\d{9}$/',
        'captcha' => 'required|captcha',
        'password' => ['required', 'string', 'min:6', 'max:16', 'regex:/^(?=.*[A-Za-z])(?=.*\d).+$/'],
    ];

    protected array $validateMessages = [
        'phone.required' => '请输入手机号',
        'phone.regex' => '请输入正确的手机号',
        'captcha.required' => '请输入图形验证码',
        'captcha.captcha' => '请输入正确的图形验证码',
        'password.required' => '请输入密码',
        'password.min' => '密码长度不能小于6',
        'password.max' => '密码长度不能大于16',
        'password.regex' => '密码必须包含字母和数字',
    ];

    public function __construct(Request $request,AdminRepository $adminRepository)
    {
        $this->request = $request;
        $this->repository = $adminRepository;
    }

    public function authenticate(LoginLogRepository $loginLogRepository)
    {
        $prams = $this->validate($this->request, $this->validateRules, $this->validateMessages);

        $admin = $this->repository->getByPhone($prams['phone']);

        if (!$admin) {
            $loginLogRepository->log([
                'name' => $prams['phone'],
                'browser' => $this->request->header('user-agent'),
                'status' => 0,
                'message' => '账号不存在',
                'login_ip' => $this->request->ip(),
                'login_at' => now(),
                'user_agent' => $this->request->header('user-agent') ?? '',
                'referer' => $this->request->header('referer') ?? '',

            ]);
            return back()->withErrors([
                'phone' => '账号或密码不正确',
            ]);
        }

        if (!Hash::check($prams['password'], $admin->password)) {
            $loginLogRepository->log([
                'user_id' => $admin->id,
                'name' => $prams['phone'],
                'browser' => $this->request->header('user-agent'),
                'status' => 0,
                'message' => '密码错误',
                'login_ip' => $this->request->ip(),
                'login_at' => now(),
                'user_agent' => $this->request->header('user-agent') ?? '',
                'referer' => $this->request->header('referer') ?? '',

            ]);
            return back()->withErrors([
                'phone' => '账号或密码不正确',
            ]);
        }

        if ($admin->status != 1) {
            $loginLogRepository->log([
                'user_id' => $admin->id,
                'name' => $prams['phone'],
                'browser' => $this->request->header('user-agent'),
                'status' => 0,
                'message' => '账号已被禁用',
                'login_ip' => $this->request->ip(),
                'login_at' => now(),
                'user_agent' => $this->request->header('user-agent') ?? '',
                'referer' => $this->request->header('referer') ?? '',
            ]);
            return back()->withErrors([
                'phone' => '账号已被禁用',
            ]);
        }

        auth()->guard('admin')->login($admin);

        $admin->last_login_at = now();
        $admin->last_login_ip = $this->request->ip();
        $admin->save();
        $loginLogRepository->log([
            'user_id' => $admin->id,
            'name' => $prams['phone'],
            'browser' => $this->request->header('user-agent'),
            'status' => 1,
            'message' => '登录成功',
            'login_ip' => $this->request->ip(),
            'login_at' => now(),
            'user_agent' => $this->request->header('user-agent') ?? '',
            'referer' => $this->request->header('referer') ?? '',
        ]);

        return redirect()->route('admin.dashboard');
    }

    public function login()
    {
        if(auth()->guard('admin')->check()){
            return redirect()->route('admin.dashboard');
        }
        return $this->inertia('admin/auth/login');
    }

    public function logout()
    {
        auth()->guard('admin')->logout();
        return redirect()->route('admin.login');
    }

    public function clearCache()
    {
        Cache::flush();
        return $this->responseSuccess();
    }
}
